package com.jiayou.config

import cn.hutool.core.util.RandomUtil
import cn.hutool.crypto.digest.BCrypt
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import java.beans.ConstructorProperties
import java.time.LocalDateTime
import javax.annotation.PostConstruct


/**
@author 李 双
@data   2021-04-02  10:56:16
@info
 */
@Component
class GateWayGlobalFilter : GlobalFilter, Ordered {

    @JvmField
    final var logger: Logger = LoggerFactory.getLogger(GateWayGlobalFilter::class.java)


    @Value("${'$'}{auth.code}")
    private lateinit var code: String

    @Autowired
    private lateinit var stringRedisTemplate: StringRedisTemplate

    @JvmField
    final val SOURCE: String = RandomUtil.randomString(1024)


    @PostConstruct
    fun addAuthAccessCode() = stringRedisTemplate.opsForValue().set(code, SOURCE).also { logger.info("已更新特征值！") }

    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点更新一次特征码
    fun configureAuthCode() {
        stringRedisTemplate.opsForValue().set(code, SOURCE)
        logger.info("已更新特征值！")
    }

    override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
        val access = BCrypt.hashpw(SOURCE, BCrypt.gensalt())
        return chain.filter(exchange.mutate().request(exchange.request.mutate().header(code, access).build()).build())
    }


    override fun getOrder() = -999


}